package com.telit.firecommand.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.telit.common.enums.ResultCode;
import com.telit.common.exception.ForestBaseException;
import com.telit.common.util.JwtTokenUtils;
import com.telit.firecommand.dao.CommRoamingLineDao;
import com.telit.firecommand.entity.CommRoamingLine;
import com.telit.firecommand.service.RoamingLineService;
import com.telit.firecommand.service.UserInfoService;
import com.telit.upms.vo.MicroCustomRoleInfoVo;
import com.telit.upms.vo.MicroSysUserAllInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Auther amy
 * @Describe
 */
@Service
public class RoamingLineServiceImpl implements RoamingLineService {

    @Autowired
    private CommRoamingLineDao commRoamingLineDao;

    @Autowired
    private UserInfoService userInfoService;

    @Override
    public IPage<CommRoamingLine> listByPage(Integer current, Integer size, CommRoamingLine commRoamingLine) {
        IPage<CommRoamingLine> iPage = new Page<>(current, size);
        return commRoamingLineDao.selectPage(iPage, getWrapper(commRoamingLine));
    }

    @Override
    public List<CommRoamingLine> listNoPage(CommRoamingLine commRoamingLine) {
        //2022-05-18 优化 避免过度请求 -------fixed by yzx-------start
        /*List<CommRoamingLine> list = commRoamingLineDao.selectList(getWrapper(commRoamingLine));
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(line -> {
                if (line.getCreateUser() != null) {
                    SysUserDetailVo user = userInfoService.getUserInfo(line.getCreateUser());
                    if (user != null) {
                        List<SysRoleVo> listVo = user.getRoles();

                        if (!CollectionUtils.isEmpty(listVo)) {
                            List<String> roleList = new ArrayList<>();
                            System.out.println(org.apache.commons.lang.StringUtils.join(roleList.toArray(), ","));
                            listVo.forEach(vo -> roleList.add(vo.getRoleName()));
                            line.setCreateUserRole(org.apache.commons.lang.StringUtils.join(roleList.toArray(), ","));
                        }
                        line.setCreateUserName(user.getRealName());
                    }
                }
            });
        }
        return list;*/
        List<CommRoamingLine> list = commRoamingLineDao.selectList(getWrapper(commRoamingLine));
        if (!CollectionUtils.isEmpty(list)) {
            List<Long> ids = list.stream().map(CommRoamingLine::getCreateUser).collect(Collectors.toList());
            List<MicroSysUserAllInfoVo> microSysUserAllInfoVos = userInfoService.queryUserInfoByIds(ids);
            Map<Long, MicroSysUserAllInfoVo> sysUserAllInfoVoMap = microSysUserAllInfoVos.stream().collect(
                    Collectors.toMap(MicroSysUserAllInfoVo::getId, Function.identity(), (key1, key2) -> key2));
            list.forEach(line -> {
                if (line.getCreateUser() != null) {
                    MicroSysUserAllInfoVo user = sysUserAllInfoVoMap.get(line.getCreateUser());
                    if (user != null) {
                        List<MicroCustomRoleInfoVo> convertList = user.getConvertList();
                        if (!CollectionUtils.isEmpty(convertList)) {
                            List<String> roleList = new ArrayList<>();
                            convertList.forEach(vo -> roleList.add(vo.getRoleName()));
                            line.setCreateUserRole(org.apache.commons.lang.StringUtils.join(roleList.toArray(), ","));
                        }
                        line.setCreateUserName(user.getRealName());
                    }
                }
            });
        }
        return list;
        //2022-05-18 优化 避免过度请求 -------fixed by yzx-------end
    }

    @Override
    public void add(CommRoamingLine commRoamingLine) {
        // 判断名称是否重复
        isExistName(commRoamingLine);
        commRoamingLine.setCreateUser(JwtTokenUtils.getId());
        commRoamingLine.setCreateTime(new Date());
        if (commRoamingLineDao.insert(commRoamingLine) <= 0) {
            throw new ForestBaseException(ResultCode.OPERATE_ERROR.getCode(), "新增漫游路线失败");
        }
    }

    @Override
    public CommRoamingLine detail(Long id) {
        return commRoamingLineDao.selectById(id);
    }

    @Override
    public void update(CommRoamingLine commRoamingLine) {
        // 判断名称是否重复
        isExistName(commRoamingLine);
        commRoamingLine.setUpdateUser(JwtTokenUtils.getId());
        commRoamingLine.setUpdateTime(new Date());
        if (commRoamingLineDao.updateById(commRoamingLine) <= 0) {
            throw new ForestBaseException(ResultCode.OPERATE_ERROR.getCode(), "修改漫游路线失败");
        }
    }

    @Override
    public void deleteBatch(List<Long> ids) {
        if (!CollectionUtils.isEmpty(ids)) {
            if (commRoamingLineDao.deleteBatchIds(ids) <= 0) {
                throw new ForestBaseException(ResultCode.OPERATE_ERROR.getCode(), "删除漫游路线失败");
            }
        }
    }

    /**
     * 条件查询
     *
     * @return
     */
    public QueryWrapper<CommRoamingLine> getWrapper(CommRoamingLine commRoamingLine) {
        QueryWrapper<CommRoamingLine> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(commRoamingLine.getName())) {
            queryWrapper.like("name", commRoamingLine.getName());
        }

        queryWrapper.orderByDesc("create_time");
        queryWrapper.eq("deleted", "0");
        return queryWrapper;
    }

    /**
     * 判断名称是否重复
     */
    private void isExistName(CommRoamingLine commRoamingLine) {
        QueryWrapper<CommRoamingLine> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", commRoamingLine.getName());
        queryWrapper.eq("deleted", "0");
        if (commRoamingLine.getId() != null) {
            queryWrapper.ne("id", commRoamingLine.getId());
        }
        Integer roamingLineCount = commRoamingLineDao.selectCount(queryWrapper);
        if (roamingLineCount > 0) {
            throw new ForestBaseException(ResultCode.OPERATE_ERROR.getCode(), "漫游名称已经存在");
        }
    }
}
